//
//  SCConfirmRefundController.m
//  shangcheng
//
//  Created by 张艳江 on 2019/6/11.
//  Copyright © 2019 张艳江. All rights reserved.
//

#import "SCConfirmRefundController.h"
#import "WCLActionSheet.h"
#import "MessageTextView.h"
#import "UploadImageCell.h"
#import "TZImagePickerHelper.h"

#define MAX_COUNT 3

@interface SCConfirmRefundController ()<WCLActionSheetDelegate,UICollectionViewDelegate,UICollectionViewDataSource>

@property (weak, nonatomic) IBOutlet UILabel *goodsStateLab;
@property (weak, nonatomic) IBOutlet UILabel *reasonLab;
@property (weak, nonatomic) IBOutlet UILabel *priceLab;
@property (weak, nonatomic) IBOutlet UIView *textBgView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (strong, nonatomic) NSString *type_id;
@property (strong, nonatomic) NSArray  *reasonArray;
@property (strong, nonatomic) NSString *goods_status;
@property (strong, nonatomic) NSArray  *goodsStateArray;

@property (strong, nonatomic) MessageTextView     *textView;
@property (strong, nonatomic) NSMutableArray      *imagesFiles;
@property (strong, nonatomic) TZImagePickerHelper *helper;
@property (strong, nonatomic) NSMutableArray      *upImagesData;

@end

@implementation SCConfirmRefundController

- (NSMutableArray *)imagesFiles{
    if (!_imagesFiles) {
        _imagesFiles = [NSMutableArray array];
    }
    return _imagesFiles;
}
- (NSMutableArray *)upImagesData{
    if (!_upImagesData) {
        _upImagesData = [NSMutableArray array];
    }
    return _upImagesData;
}
- (TZImagePickerHelper *)helper{
    if (!_helper) {
        _helper = [[TZImagePickerHelper alloc] init];
        WeakSelf;
        dispatch_group_t group = dispatch_group_create();
       
        _helper.finish = ^(NSArray *array, BOOL isEnd){
            
            [SVProgressHUD showWithStatus:@"上传中..."];
            
            [weakSelf.imagesFiles addObjectsFromArray:array];
            
            dispatch_group_enter(group);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                UIImage *image = [UIImage imageWithContentsOfFile:array[0]];
                NSString *url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GiftAppOrder&a=upload"];
                [[NetworkRequestTool sharedNetworkTool] uploadWithURL:url parameters:nil images:@[image] name:@"file" fileName:nil mimeType:@"image/png" progress:nil success:^(id result, NSString *error) {
                    //NSLog(@"----%@",result);
                    if ([result[@"status"] isEqualToString:@"true"]) {
                        [weakSelf.upImagesData addObject:result[@"info"]];
                        [weakSelf.collectionView reloadData];
                        if (isEnd == YES) {
                            [SVProgressHUD dismiss];
                        }
                        dispatch_group_leave(group);
                    }else{
                        [weakSelf.upImagesData removeAllObjects];
                        [SVProgressHUD showImage:nil status:result[@"info"]];
                        dispatch_group_leave(group);
                        return ;
                    }
                } failure:^(NSError *error) {
                    [weakSelf.upImagesData removeAllObjects];
                    [SVProgressHUD showImage:nil status:@"上传失败，请检查您的网络连接"];
                    dispatch_group_leave(group);
                    return ;
                }];
            });
        };
    }
    return _helper;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"退款退货";
    if ([self.goodsModel.type intValue] == 1) {//积分商城
        self.priceLab.text = [NSString stringWithFormat:@"%@福豆",self.goodsModel.sum];
    }
    self.type_id = @"";
    self.goods_status = @"";
    self.textBgView.layer.cornerRadius = 5.0f;
    self.textBgView.layer.borderColor = RGB(239, 239, 239).CGColor;
    self.textBgView.layer.borderWidth = 0.7;
    
    self.textView = [[MessageTextView alloc]initWithFrame:CGRectMake(0, 0, kScreenW - 24, 90) text:@"请您在此描述您的问题(最多80字)" isLimit:YES];
    self.textView.limitNum = 80;
    [self.textBgView addSubview:self.textView];
    
    //获取退款状态
    [self requestReasonData];
    
    //set Collection
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumLineSpacing = 8;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;//滚动方向
    
    layout.itemSize = CGSizeMake(80, 80);
    
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    //定义xib文件
    [self.collectionView registerNib:[UINib nibWithNibName:@"UploadImageCell" bundle:nil] forCellWithReuseIdentifier:@"UploadImageCellID"];
}
- (void)requestReasonData{
    
    NSDictionary *dict = @{@"token":Token};
    NSString *url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GiftAppOrder&a=App_Services"];
    [SVProgressHUD showWithStatus:@"加载中..."];
    [[NetworkRequestTool sharedNetworkTool] POST:url parameters:dict finished:^(id result, NSString *error) {
        [SVProgressHUD dismiss];
        self.reasonArray = [SCModel mj_objectArrayWithKeyValuesArray:result[@"data"]];
        //NSLog(@"---%@",result);
    }];
}
- (IBAction)clickBtns:(UIButton *)sender {
    
    if (sender.tag == 0) {//货物状态
        
        self.goodsStateArray = @[@"未收到货",@"已收到货"];
        WCLActionSheet *actionSheet = [[WCLActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"未收到货",@"已收到货",nil];
        actionSheet.tag = 0;
        UIWindow *window=[UIApplication sharedApplication].keyWindow;
        [actionSheet showInView:window];
    }else{//选择退款原因
        NSMutableArray *reasons = [NSMutableArray array];
        for (SCModel *model in self.reasonArray) {
            [reasons addObject:model.content];
        }
        WCLActionSheet *actionSheet = [[WCLActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:[[reasons copy] componentsJoinedByString:@","],nil];
        actionSheet.tag = 1;
        UIWindow *window=[UIApplication sharedApplication].keyWindow;
        [actionSheet showInView:window];
    }
}
- (void)actionImageSheet:(WCLActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (actionSheet.tag == 0) {
        self.goods_status = [NSString stringWithFormat:@"%d",buttonIndex];
        self.goodsStateLab.text = self.goodsStateArray[buttonIndex];
    }else{
        SCModel *model = self.reasonArray[buttonIndex];
        self.type_id = model.type_id;
        self.reasonLab.text = model.content;
    }
}
#pragma mark  --------UICollectionVIew 的代理方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.imagesFiles.count == 3) {
        return self.imagesFiles.count;
    }
    return self.imagesFiles.count + 1;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UploadImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UploadImageCellID" forIndexPath:indexPath];
    
    if (indexPath.row == self.imagesFiles.count){
        cell.img_pic.image = [UIImage imageNamed:@"shangchuantupian"];
        cell.btn_del.hidden = YES;
    }else{
        cell.img_pic.image = [UIImage imageWithContentsOfFile:self.imagesFiles[indexPath.row]];
        cell.btn_del.hidden = NO;
    }
    cell.img_pic.contentMode =  UIViewContentModeScaleAspectFill;
    
    [cell.btn_del addTarget:self action:@selector(onDelClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.btn_del.tag = indexPath.row;
    
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.view endEditing:YES];
    if (indexPath.row == self.imagesFiles.count){
        
        if ((MAX_COUNT - self.imagesFiles.count) <= 0) return;
        
        [self.helper showImagePickerControllerWithMaxCount:(MAX_COUNT - self.imagesFiles.count) WithViewController:self];
    }else{
        // preview photos or video / 预览照片或者视频
    }
}
#pragma mark ----删除图片
-(void)onDelClick:(UIButton *)sender{
    [self.imagesFiles removeObjectAtIndex:sender.tag];
    [self.upImagesData removeObjectAtIndex:sender.tag];
    [self.collectionView reloadData];
}
#pragma mark
- (IBAction)clickSubmitBtn:(id)sender {
    
    if (self.goods_status.length == 0) {
        [SVProgressHUD showImage:nil status:@"请选择货物状态"];
        return;
    }
    if (self.type_id.length == 0) {
        [SVProgressHUD showImage:nil status:@"请选择退货原因"];
        return;
    }
    if (self.textView.text.length == 0) {
        [SVProgressHUD showImage:nil status:@"请填写退款说明"];
        return;
    }
    if (self.upImagesData.count == 0) {
        [SVProgressHUD showImage:nil status:@"请上传图片"];
        return;
    }
    
    NSDictionary *dict = @{@"type":self.goodsModel.type,
                           @"token":Token,
                           @"order_id":self.goodsModel.order_id,
                           @"status":self.status,
                           @"type_id":self.type_id,
                           @"content":self.textView.text,
                           @"wap_pic":[[self.upImagesData copy] componentsJoinedByString:@","],
                           @"goods_status":self.goods_status};
    //NSLog(@"提交的数据%@",dict);
    NSString *url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GiftAppOrder&a=App_Service"];
    [SVProgressHUD showWithStatus:@"提交中..."];
    [[NetworkRequestTool sharedNetworkTool] POST:url parameters:dict finished:^(id result, NSString *error) {
        [SVProgressHUD showSuccessWithStatus:@"提交成功"];
        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
    }];
}


@end
